package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author buyandalai
 */
public class chatHandler extends Thread {
    private Socket socket;
    InputStream sin = null;
    OutputStream sout = null;
    DataInputStream in = null;
    DataOutputStream out = null;
    chatHandlerWindow chw = null;

    public chatHandler(Socket socket){
        this.socket = socket;
    }

    public String getRemoteIpAddress()
    {
        return socket.getInetAddress().getHostAddress();
    }

    public void sendMessage(String msg)
    {
        try {
            out.writeUTF(msg);
            out.flush();
        } catch (IOException ex) {
            Logger.getLogger(chatHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void closeSocket()
    {
        try {
            this.socket.close();
        } catch (IOException ex) {
            Logger.getLogger(chatHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run()
    {
        chw = new chatHandlerWindow(this);
        chw.setVisible(true);
        try {
            sin = socket.getInputStream();
            sout = socket.getOutputStream();
            in = new DataInputStream(sin);
            out = new DataOutputStream(sout);
            while(true){
                chw.clientMessage(in.readUTF());
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                sin.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
